package com.aaa.service.impl;

import com.aaa.common.domain.UserInfo;
import com.aaa.common.domain.UserLogin;
import com.aaa.common.domain.UserRole;
import com.aaa.common.query.UserInfoQuery;
import com.aaa.common.result.Result;
import com.aaa.mapper.UserInfoMapper;
import com.aaa.mapper.UserLoginMapper;
import com.aaa.service.UserInfoService;
import com.aaa.util.GFSStringUtil;
import com.aaa.util.PasswordUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private UserInfoMapper mapper;

    @Autowired
    private UserLoginMapper userLoginMapper;

    /**
     * 分页查询用户表
     * @param userInfoQuery
     * @return
     */
    public Result listUser(UserInfoQuery userInfoQuery) {
        Page<UserInfo> page = new Page<>(userInfoQuery.getPage(),userInfoQuery.getCount());
        QueryWrapper<UserInfo> qw = new QueryWrapper<>();
        //如果模糊查询内容不为空 加上模糊查询
        qw.like(GFSStringUtil.StrNotNull(userInfoQuery.getName()),"name",userInfoQuery.getName());
        qw.gt(GFSStringUtil.IntegerNotNull(userInfoQuery.getMinAge()),"age",userInfoQuery.getMinAge());
        qw.lt(GFSStringUtil.IntegerNotNull(userInfoQuery.getMaxAge()),"age",userInfoQuery.getMaxAge());
        qw.eq("state",1);
        Page<UserInfo> userInfoPage = mapper.selectPage(page, qw);
        return Result.success(userInfoPage);
    }

    /**
     * 用户表添加
     * @param datas
     * @return
     */
    @Transactional
    public Result addUser(Map<String,Object> datas) {
        //添加用户登陆表
        //获取前端传过来用户信息表的信息
        Map<String,String> userAdd = (Map<String, String>) datas.get("userAdd");
        String name = userAdd.get("name");
        String ages = userAdd.get("age");
        int age = Integer.parseInt(ages);
        String sex = userAdd.get("sex");
        String phones = userAdd.get("phone");
        int phone = Integer.parseInt(phones);
        //获取从前端传过来的用户登录表的信息
        Map<String,String> userInfoAdd = (Map<String, String>) datas.get("userInfoAdd");
        String username = userInfoAdd.get("username");
        String pwd = userInfoAdd.get("password");
        //判断该用户是否已存在 如果存在不能添加
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("state",1);
        List<UserInfo> userInfos = mapper.selectList(wrapper);
        for (UserInfo userInfo : userInfos) {
            if (name.equals(userInfo.getName())){
                return Result.error("对不起 该用户已存在");
            }
        }
        //随机生成盐
        String salt = new SecureRandomNumberGenerator().nextBytes().toString();
        //密码加密
        String password = PasswordUtil.secret(pwd, salt);
        //判断登录信息表是否存在 存在不能添加
        QueryWrapper<UserLogin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("state",1);
        List<UserLogin> userLogins = userLoginMapper.selectList(queryWrapper);
        for (UserLogin userLogin : userLogins) {
            if (username.equals(userLogin.getUsername())){
                return Result.error("对不起 已经有该账号");
            }
        }
        //往用户信息表里面插入信息
        int i = userLoginMapper.insertUserLogin(username, password, salt);
        //获取登陆表的主键
        int userLoginId = userLoginMapper.getUserLoginId(username);
        //添加用户信息
        int userInfo = mapper.insertUserInfo(name, age, sex, phone, userLoginId);
        //获取角色id
        Object roleNames = datas.get("roleNames");
        String string = roleNames.toString();
        System.out.println("++++++++++++++++++++++++++"+string);
        //拆分传过来的id数组
        String substring = string.substring(1);
        String s = substring.substring(0, substring.length() - 1);
        String[] split = s.split(",");
        //根据用户名获取用户表的id
        int uid = mapper.queryIdByName(name);
        for (String rid : split) {
            int insertUserRole = mapper.insertUserRole(uid, rid);
            if (insertUserRole<0){
                return Result.success("添加失败");
            }
        }
        return Result.success("添加成功");
    }

    /**
     * 通过id查询用户信息表和角色表数据
     * @param id
     * @return
     */
    @Override
    public Result queryUFById(Integer id) {
        //通过id查询用户信息表数据
        List<UserRole> userInfos = mapper.queryUserInfoRoleById(id);
        return Result.success(userInfos);
    }



    /**
     * 用户表修改
     * @param userInfo
     * @return
     */
    public boolean updateUser(UserInfo userInfo) {
        int updateById = mapper.updateById(userInfo);
        if (updateById>0){
            return true;
        }
        return false;
    }

    /**
     * 用户表删除
     * @param ids
     * @return
     */
    @Transactional
    public Result deleteUser(String ids) {
        //拆分前端传过来的id
        String[] split = ids.split(",");
        //将数组转换成list集合
        List<String> strings = Arrays.asList(split);
        //当传过来的id是1的话不能删除 1是管理员
        for (String string : strings) {
            if (strings.contains("1")){
                return Result.error("管理员不能够删除");
            }
        }

        boolean delete = mapper.deleteUserInfo(strings);
        if (delete==true){
            //删除用户信息表
            //获取该用户的登录id 用来删除对应的登录信息表
            List<String> loginId = mapper.selectLoginId(strings);
            for (String s : loginId) {
                System.out.println("=================");
                System.out.println(loginId);
                System.out.println("=================");
            }
            boolean b1 = mapper.deleteUserLogin(loginId);
            if (b1==true){
                //删除用户角色中间表
                boolean b = mapper.deleteUserRole(strings);
                return Result.success("删除成功");
            }
        }
        return Result.error("删除失败");
    }
}
